package com.example.demo.service;

import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;

import org.springframework.stereotype.Service;

import com.example.demo.dto.FileUploadChunkDTO;
import com.example.demo.model.FileUploadCompleteData;
import com.example.demo.model.SessionInitialRes;
import com.example.demo.util.HashExample;

import io.micrometer.common.util.StringUtils;

@Service
public class FileUploadService {

	private final FileStorageService fileStorageService;

	private final int Timeout = 8 * 3600 * 10000; // 会话时限

	public FileUploadService(FileStorageService fileStorageService) {
		this.fileStorageService = fileStorageService;
	}

	public SessionInitialRes handleFileRegistration() {
		String sessionID = UUID.randomUUID().toString();
		setSessionTimepiece(sessionID);
		boolean success = fileStorageService.createFileStorage(sessionID);
		SessionInitialRes response = new SessionInitialRes();
		response.setSessionID(sessionID);
		response.setSuccess(success);
		return response;
	}

	/**
	 * 会话计时器 超时清理资源
	 */
	private void setSessionTimepiece(String sessionID) {
		Timer timer = new Timer();
		TimerTask task = new TimerTask() {
			@Override
			public void run() {
				releaseSession(sessionID);
			}
		};

		timer.schedule(task, Timeout);
	}

	private void releaseSession(String sessionID) {
		fileStorageService.deleteSession(sessionID);
	}

	public boolean handleSubmitChunkInspect(Boolean succeedInspect, Boolean succeedUpload) {
		if (!succeedInspect)
			return false;
		if (!succeedUpload)
			return false;
		return true;
	}

	public boolean handleFileInspect(FileUploadChunkDTO chunkDTO) {
		String hash = HashExample.compute(chunkDTO.getChunkData(), chunkDTO.getAlgorithm());
		String hashSource = chunkDTO.getChunkHash();
		if (StringUtils.isBlank(hash))
			return false;
		if (!hash.equals(hashSource))
			return false;
		return true;
	}

	public boolean handleChunkUpload(FileUploadChunkDTO chunkDTO) {
		return fileStorageService.storeChunk(chunkDTO.getSessionID(), chunkDTO.getChunkIndex(),
				chunkDTO.getChunkData());

	}

	public void handleRefuseChunk(String sessionID, String chunkIndex) {
		fileStorageService.deleteChunk(sessionID, chunkIndex);
	}

	public boolean handleFileAssembly(FileUploadCompleteData metaData) {
		String sessionID = metaData.getSessionID();
		String name = metaData.getName();
		String suffix = metaData.getSuffix();
		return fileStorageService.assembleFile(sessionID, name, suffix);

	}

	public boolean handleFileRegister(FileUploadCompleteData metaData) {
		fileStorageService.registerFile(metaData);
		return true;
	}
}
